package com.imonsoft.common.util;

import java.io.UnsupportedEncodingException;
import java.util.ResourceBundle;

import sun.misc.BASE64Decoder;

/**
 * 字符集转换工具类
 * 
 * @author LiQianHui
 * @version 2013
 */
public class EncodeUtils {

	private EncodeUtils() {
	}

	private static String TOCODE = null;
	private static String FROMCODE = null;
	static {
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("encode");
			TOCODE = bundle.getString("to");
			FROMCODE = bundle.getString("from");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 从中文转向其它码,无编码指定则读配置
	 * 
	 * @param str
	 * @return string
	 */
	public static String fromChinese(String str) {
		return fromChinese(str, TOCODE, FROMCODE);
	}

	/**
	 * 从中文转向其它码
	 * 
	 * @param str
	 * @param fromCode
	 * @param toCode
	 * @return string
	 */
	public static String fromChinese(String str, String fromCode, String toCode) {
		try {
			if (str != null)
				return new String(str.getBytes(fromCode), toCode);
		} catch (UnsupportedEncodingException ue) {
			System.out.println(ue.toString());
		}
		return str;
	}

	/**
	 * 转中文,无指定码则读配置
	 * 
	 * @param str
	 * @return string
	 */
	public static String toChinese(String str) {
		return toChinese(str, FROMCODE, TOCODE);
	}

	/**
	 * 转中文,按指定的调用参数来转码
	 * 
	 * @param str
	 * @param fromCode
	 * @param toCode
	 * @return string
	 */
	public static String toChinese(String str, String fromCode, String toCode) {
		try {
			if (str != null) {
				return new String(str.getBytes(fromCode), toCode);
			}
		} catch (UnsupportedEncodingException ue) {
			System.out.println(ue.toString());
		}
		return str;
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}

	// 将 s 进行 BASE64 编码
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}

	public static void main(String[] args) {
		String str = "Rm9yIGlucHV0IHN0cmluZzogIiI=";
		System.out.println(EncodeUtils.getFromBASE64(str));
	}
}
